<template>
    <div class="mainContent">
        <path-tracking :path='path' />
        <div class="pageContent">
            <p @click="createBtn" v-if="createBtns" class="createBtn"><img src="@/assets/img/button_plus.png" class="iconPlus" />现场预约</p>
            <div style="background: #FFF;border-radius: 8px;">
                <div class="common-table-title">
                    <div class="common-table-icon"></div>
                    <div class="common-table-fl">查询条件</div>
                </div>
            
                <advanced-search
                    ref="advancedSearch"
                    :option="filterOption"
                    @onSearch="debounceRequest"
                    @phoneSearch="phoneSearch"
                />
            </div>
            <!-- 列表标题&操作按钮 -->
            <el-row style="margin-top: 1.5rem;">
                <div class="common-table-title">
                    <div class="common-table-icon"></div>
                    <div class="common-table-fl">待处理列表</div>
                </div>
            </el-row>
            <el-row style="padding: 0 16px;background: #FFF;border-radius: 0 0 8px 8px;">
                <el-table
                    :data="scheduledListData"
                    :row-style="selectedHighlight"
                    max-height="550"
                    ref="recordList"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column
                        v-for='(item, index) in scheduledListItem'
                        :key="index"
                        :prop='item.prop'
                        :label='item.label'
                        :width="item.width"
                        align='center'
                    >
                        <template slot-scope="scope">
                            <div>
                                {{translateData(scope.row, item)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="240"
                        align='center'
                    >
                        <template slot-scope="scope">
                            <div class="btnsCan">
                                <div v-if="seeDetailBtn" @click="seeDetail(scope.row)" class="operateBtn check">
                                    查看
                                </div>
                                <div @click="clickBtn(scope.row)" class="operateBtn edit" v-if="judgeStatus(scope.row) && followUp">
                                    跟进
                                </div>
                                <div @click="goTreat(scope.row)" class="operateBtn verify" v-if="judgeStatus(scope.row) && treat">
                                    接待
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-row class="pagination-cont">
                    <el-pagination
                        @size-change="handleSizeChange"
                        background
                        @current-change="handleCurrentChange"
                        :current-page="currentPageIndex"
                        :page-sizes="pageSizeList"
                        :page-size="currentPageSize"
						:pager-count="5"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                    />
                </el-row>
            </el-row>
            <phone-search-popup 
                ref="phoneSearchPopup"
                :sourceList="sourceList"
                :currentShop="currentShop"
                :currentLocate="currentLocate"
            />
        </div>
    </div>
</template>
<script>
import pathTracking from '@/components/common/pathTracking'
import advancedSearch from '@/components/common/filter/advancedSearch.vue'
import datas from './datas.js'
import phoneSearchPopup from './phoneSearchPopup'
// 获取按钮权限配置的方法
import operationConfig from '@/utils/btnsPermission'
import { DRcookie } from '@/assets/js/common.js'
import { getPendingOrders, getResource, checkPhone, getCurrentShop, getFollowUpList } from './axios.js'
export default {
    name: 'bookedCustomer',
    data() {
        return{
            path: ['CRM', '预约管理', '预约接待'],
            // 当前状态
            currentStatus: '',
            currentSearchClue: '',
            // 搜索条件
            filterOption: _.cloneDeep(datas.filterOption),
            // 三种状态的参数
            statusConfig: datas.statusConfig,
            // 当前每页显示的条数
            currentPageSize: 10,
            pageSizeList: [10, 20, 30, 40],
            total: 0,
            // 当前页码
            currentPageIndex: 1,
            // 预约列表项
            scheduledListItem: datas.scheduledListItem,
            // 预约列表内容
            scheduledListData: [],
            // 选中项的数组
            TableSelectData: [],
            sourceList: [],
            // 当前门店、地址
            currentShop: '',
            currentLocate: '',
            timer: null,

            createBtns: false,
            seeDetailBtn: false,
            followUp: false,
            treat: false
        }
    },
    components: {
        pathTracking,
        advancedSearch,
        phoneSearchPopup
    },
    methods: {
        // 点击搜索
        toSearch() {
            let obj = {}
            // 到店的是2 
            obj.type = 2
            // 待处理
            obj.auditingStatus = 4
            let val = this.$refs.advancedSearch.getFormData();
            let doSearch = false
            val.map(ele => {
                if(ele.value !== '' && ele.value != undefined) {
                    doSearch = true
                    if(ele.key === 'createTime') {
                        obj.createTimeStart = new Date(ele.value[0]).getTime()
                        obj.createTimeEnd = new Date(ele.value[1]).getTime() + 24 * 60 * 60 * 1000 - 1000
                    }else if(ele.key === 'reservationTime') {
                        obj.reservationStartTimeQuery = new Date(ele.value[0]).getTime()
                        obj.reservationEndTimeQuery = new Date(ele.value[1]).getTime()
                    }else {
                        obj[ele.key] = ele.value
                    }
                }
            })
            let param = {
                condition: obj,
                pageIndex: this.currentPageIndex,
                pageSize: this.currentPageSize,
                pageTotal: 5,
                total: 0
            }
            getPendingOrders(param).then(res => {
                if(res.data.status === 200) {
                    this.scheduledListData = res.data.result.result
                    this.total = res.data.result.total
                }else {
                    this.$message({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            }).catch(err => {
                this.$message({
                    showClose: true,
                    message: '查询失败',
                    type: 'error'
                });
            });
        },
        // 获取预约来源
        async getResourceInfo() {
            getResource().then(res => {
                if(res.status === 200) {
                    this.sourceList = res.data.result
                    let arr = [{
                        label: '请选择预约来源',
                        value: undefined
                    }]
                    res.data.result.map(ele => {
                        let obj = {}
                        obj.value = ele.value
                        obj.label = ele.value
                        arr.push(obj)
                    })
                    this.filterOption.items.forEach(ele => {
                        if(ele.key === 'source') {
                            ele.data = arr
                        }
                    });
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // 获取跟进人列表
        getFollowUp() {
            getFollowUpList().then(res => {
                if(res.data.status === 200) {
                    let arr = [{
                        label: '请选择创建人',
                        value: undefined
                    }]
                    res.data.result.map(ele => {
                        arr = arr.concat({
                            label: ele.userName,
                            value: ele.sapUserId
                        })
                    })
                    this.filterOption.items.map(ele => {
                        ele.key === 'createBy' && (ele.data = arr)
                    })
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // 手机快捷查询
        phoneSearch(data) {
            let shopCode = DRcookie.get('shopCode')
            if(shopCode == 'null') {
                this.$message({
                    message: '您不是门店用户，无法使用手机快捷查询！',
                    type: 'warning'
                })
                return
            }
            if(data.phone) {
                spinner.text = '验证中...'
                checkPhone(data.phone, 2).then(res => {
                    if(res.data.status === 200) {
                        let infoType = res.data.result.infoType;
                        if(infoType === 1) {
                            this.$refs.phoneSearchPopup.openBox(res.data.result);
                        }else if(infoType === 2) {
                            this.$refs.phoneSearchPopup.openBox(res.data.result);
                        }else if(infoType === 3) {
                            this.$message({
                                message: '无该客户信息',
                                type: 'warning',
                                showClose: true
                            })
                        }
                    }
                }).catch(err => {
                    console.log('err: ', err)
                })
            }else {
                this.$message({
                    message: '请输入手机号后再查询',
                    type: 'warning',
                    showClose: true
                })
            }
        },
        // 创建预约
        createBtn() {
            let shopCode = DRcookie.get('shopCode')
            if(shopCode == 'null') {
                this.$message({
                    message: '您不是门店用户，无法创建现场预约单！',
                    type: 'warning'
                })
                return
            }
            this.$router.push({path: 'operateOrderShop', query: {pageType: 'create'}})
        },
        // 查看
        seeDetail(param) {
            this.$router.push({name: 'seeDetailShop', query: {searchKey: param.id}})
        },
        // 跟进
        clickBtn(param) {
            this.$router.push({name: 'followUp', query: {searchKey: param.id}})
        },
        // 接待
        goTreat(param) {
            this.$router.push({name: 'treat', query: {searchKey: param.id}})
        },
        // 转义列表内容
        translateData(data, item) {
            let res = ''
            let records = data.followUpRecords,length = data.followUpRecords.length;
            switch (item.prop) {
                case 'regularCustomer':
                    data[item.prop] ? res = '是' : res = '否'
                    break;
                case 'reservationDate':
                    data.reservationStartTime && (res = data['reservationStartTime'].split(' ')[0])
                    break;
                case 'reservationTime':
                    data.reservationStartTime 
                    && data.reservationEndTime 
                    && (res = `${data.reservationStartTime.split(' ')[1]}-${data.reservationEndTime.split(' ')[1]}`)
                    break;
                case 'supportStaff':
                    if(records.length) {
                        res = records[0].supportStaff
                    }
                    break;
                case 'updateTime':
                    if(records.length) {
                        res = records[0].createTime
                    }
                    break;
                default: 
                    res = data[item.prop]
                    break;
            }
            return res
        },
        // 判断按钮是否显示
        judgeStatus(data) {
            if(data.auditingStatus == 5 || data.auditingStatus == 6 || data.auditingStatus == 7) {
                return false
            }else {
                return true
            }
        },
        // 修改?条/页
        handleSizeChange (size) {
            if(this.currentPageSize != size) {
                this.currentPageSize = size;
                this.debounceRequest();
            }
        },
        // 翻页
        handleCurrentChange (index) {
            if(this.currentPageIndex != index) {
                this.currentPageIndex = index;
                this.debounceRequest();
            }
        },
        // 调用查询接口
        debounceRequest() {
            if(this.timer) {
                clearTimeout(this.timer);
                this.timer = null
            }
            this.timer = setTimeout(() => {
                this.toSearch();
                clearTimeout(this.timer);
                this.timer = null;
            }, 300)
        },
        // 选中的数组
        handleSelectionChange (selection) {
            this.TableSelectData = selection;
        },
        // 如果选中则添加高亮样式
        selectedHighlight (data) {
            if (this.TableSelectData.indexOf(data.row) > -1) {
                return {
                    "background-color": "#FEF6EE"
                };
                return {}
            }
        },
        // 按钮权限
        btnsControl() {
            let permission = operationConfig(this.$route);
            this.createBtns = false
            this.seeDetailBtn = false
            this.followUp = false
            this.treat = false
            permission.forEach(ele => {
                if(ele.menu_name === '现场预约') {
                    this.createBtns = true
                }else if(ele.menu_name === '查看') {
                    this.seeDetailBtn = true
                }else if(ele.menu_name === '跟进') {
                    this.followUp = true
                }else if(ele.menu_name === '接待') {
                    this.treat = true
                }
                if(ele.menu_name === '手机快捷查询') {
                    this.filterOption.btnGroup = [
                        {
                            label: "查询",
                            type: "search"
                        },
                        {
                            label: "手机快捷查询",
                            type: "phoneSearch"
                        },
                        {
                            label: '清空',
                            type: 'clear'
                        }
                    ]
                }else {
                    this.filterOption.btnGroup = [
                        {
                            label: "查询",
                            type: "search"
                        },
                        {
                            label: '清空',
                            type: 'clear'
                        }
                    ]
                }
            })
        }
    },
    mounted() {
        this.getResourceInfo();
        this.getFollowUp();
        this.btnsControl();
        // 当前门店，区域
        getCurrentShop().then(res => {
            if(res.data.status === 200) {
                this.currentLocate = res.data.result.address
                this.currentShop = res.data.result.theNameOfTheStore
            }
        })
    },
    activated() {
        this.toSearch();
        // this.getResourceInfo();
        // this.getFollowUp();
        // // 当前门店，区域
        // getCurrentShop().then(res => {
        //     if(res.data.status === 200) {
        //         this.currentLocate = res.data.result.address
        //         this.currentShop = res.data.result.theNameOfTheStore
        //     }
        // })
        // this.btnsControl();
    },
    deactivated() {
        // this.filterOption = Object.assign({}, datas.filterOption)
    },
}
</script>
<style scoped>
    .pageContent{
        padding: 16px;
    }
    .iconPlus{
        width: 12px;
        height: 12px;
        margin-right: 4px
    }
    .createBtn{
        height: 40px;
        width: 100px;
        display: flex;
		align-items: center;
		justify-content: center;
        margin-bottom: 1.5rem;
        background: #7E6B5A;
        color: #FFF;
        text-align: center;
        border-radius: 20px;
        font-size: 14px;
        cursor: pointer;
    }
    .pagination-cont{
        height: 8.8rem;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;
    }
    .btnsCan{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
    .operateBtn{
        width: 5rem;
        height: 2.4rem;
        cursor: pointer;
        line-height: 2.4rem;
        border-radius: 1.2rem;
        color: #7E6B5A;
        border: 1px solid #7E6B5A;
    }
    /* .check{
        background: #7E6B5A;
        color: #FFF;
    }
    .edit{
        background: #222222;
        color: #FFF;
        border-color: #000;
    }
    .verify{
        color: #7E6B5A
    } */
    .operate-btn {
        padding: 6px 14px;
        display: inline-block;
        border-radius: 14px;
        border: solid 1px #7e6b5a;
        font-family: "Microsoft YaHei","微软雅黑","Microsoft JhengHei","华文细黑",STHeiti,MingLiu,'Avenir', Helvetica, Arial, sans-serif;
        font-size: 14px;
        color: #7e6b5a;
        cursor: pointer;
        line-height: 1;
        margin-right: 1rem;
    }
</style>
